package com.zhhtech.zhh.ui.activity.commom

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import com.zhhtech.zhh.databinding.ActivityWebviewBinding
import com.zhhtech.zhh.ui.base.BaseActivity
import com.zhhtech.zhh.ui.dialog.showAlertDialog
import com.zhhtech.zhh.ui.ext.startActivityExt
import com.zhhtech.zhh.ui.helper.InjectBundle

fun Context.openUrl(url: String?) {
    if (url != null) {
        startActivityExt<WebViewActivity> {
            putExtra(WebViewActivity.URL, url)
        }
    }
}

fun Context.openSystemUrl(url: String?) {
    if (url != null) {
        kotlin.runCatching {
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
        }
    }
}

fun Fragment.openSystemUrl(url: String?, showAlert: Boolean = false) = url?.let {
    if (showAlert) {
        showAlertDialog {
            message(message = "该功能需要跳转第三方网页，是否继续跳转？")
            negativeButton { }
            positiveButton {
                requireContext().openSystemUrl(url)
            }
        }
    } else {
        context?.openSystemUrl(url)
    }
}

class WebViewActivity : BaseActivity<ActivityWebviewBinding>() {
    companion object {
        const val URL = "url"
    }

    private val url: String by InjectBundle()

    override fun initView() {
        vb.webview.loadUrl(url)
    }

    override fun initData() {
//        Utils.invasionStatusBar(this)
        vb.webview.titleChangeListener = { vb.titleView.titleStr = it }
    }

    override fun onBackPressed() {
        if (vb.webview.canGoBack()) {
            vb.webview.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (
            KeyEvent.ACTION_DOWN == event?.action &&
            keyCode == KeyEvent.KEYCODE_BACK &&
            vb.webview.canGoBack()
        ) {
            vb.webview.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event);
    }
}